package com.smart.community.commons.config;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import java.time.Duration;

/**
 * Redis配置类
 * @author Wu.Liang
 * @since 2024-12-19
 * @version 1.0.0
 */
@Configuration
@EnableCaching
public class RedisConfig {
    
    /**
     * 配置Redis模板
     * 
     * @param connectionFactory Redis连接工厂
     * @return Redis模板
     */
    @Bean
    @ConditionalOnMissingBean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory connectionFactory) {
        RedisTemplate<String, Object> template = new RedisTemplate<>();
        template.setConnectionFactory(connectionFactory);
        
        // 设置key的序列化方式
        template.setKeySerializer(new StringRedisSerializer());
        template.setHashKeySerializer(new StringRedisSerializer());
        
        // 设置value的序列化方式，使用支持Java 8时间的序列化器
        GenericJackson2JsonRedisSerializer serializer = createJacksonSerializer();
        template.setValueSerializer(serializer);
        template.setHashValueSerializer(serializer);
        
        template.afterPropertiesSet();
        return template;
    }
    
    /**
     * 创建支持Java 8时间的Jackson序列化器
     * @return GenericJackson2JsonRedisSerializer
     */
    private GenericJackson2JsonRedisSerializer createJacksonSerializer() {
        ObjectMapper objectMapper = new ObjectMapper();
        // 注册Java 8时间模块，支持LocalDateTime等类型
        objectMapper.registerModule(new JavaTimeModule());
        // 设置所有字段可见性
        objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        // 配置忽略未知属性，避免反序列化错误
        objectMapper.configure(com.fasterxml.jackson.databind.DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        
        return new GenericJackson2JsonRedisSerializer(objectMapper);
    }
    
    /**
     * 配置缓存管理器
     * 
     * @param connectionFactory Redis连接工厂
     * @return 缓存管理器
     */
    @Bean
    public CacheManager cacheManager(RedisConnectionFactory connectionFactory) {
        // 创建支持Java 8时间的序列化器
        GenericJackson2JsonRedisSerializer serializer = createJacksonSerializer();
        
        // 创建Redis缓存配置
        RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig()
                .entryTtl(Duration.ofHours(24)) // 默认缓存24小时
                .serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(new StringRedisSerializer()))
                .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(serializer))
                .disableCachingNullValues(); // 不缓存null值

        // 创建缓存管理器
        return RedisCacheManager.builder(connectionFactory)
                .cacheDefaults(config)
                .withCacheConfiguration("region:tree", 
                    config.entryTtl(Duration.ofDays(7))) // 区域树缓存7天
                .withCacheConfiguration("user:info", 
                    config.entryTtl(Duration.ofHours(2))) // 用户信息缓存2小时
                .withCacheConfiguration("permission:menu", 
                    config.entryTtl(Duration.ofHours(4))) // 权限菜单缓存4小时
                .withCacheConfiguration("propertyCompany", 
                    config.entryTtl(Duration.ofHours(2))) // 物业公司缓存2小时
                .withCacheConfiguration("propertyCompanyList", 
                    config.entryTtl(Duration.ofHours(1))) // 物业公司列表缓存1小时
                .build();
    }
}
